package cn.virens.web.components.beetl.menu.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Stream;

public class MenuBuilder {
	public static final String ACTIVE1 = "layui-nav-itemed";
	public static final String ACTIVE2 = "layui-this";
	public static final String ACTIVE0 = "layui-none";

	private final StringBuilder builder = new StringBuilder();

	private List<MenuBuilder> childrens;
	private final String identity;
	private final Long id;

	private boolean active = false;

	public MenuBuilder(String identity, Long id) {
		this.identity = identity;
		this.id = id;
	}

	public MenuBuilder append(String... items) {
		for (String item : items) {
			builder.append(item);
		}

		builder.append("\r\n");

		return this;
	}

	public MenuBuilder append(Stream<MenuBuilder> stream) {
		stream.forEach((item) -> {
			builder.append(item.builder);
		});

		return this;
	}

	public MenuBuilder append(Collection<MenuBuilder> childrens) {
		for (MenuBuilder item : childrens) {
			builder.append(item);
		}

		builder.append("\r\n");

		return this;
	}

	public boolean isActive() {
		return active;
	}

	public boolean isActive(String other) {
		return identity.equals(other);
	}

	public String style(String other) {
		return style(isActive(other), true);
	}

	public String style(boolean children) {
		return style(active, children);
	}

	public String style(boolean active, boolean children) {
		// 检查对应的状态，返回对应的class
		if (active && children) {
			return ACTIVE2;
		} else if (active) {
			return ACTIVE1;
		} else {
			return ACTIVE0;
		}
	}

	public String icon(String other) {
		return other != null ? other : "";
	}

	public String name(String other) {
		return other != null ? other : "";
	}

	public String linkurl(String other) {
		return other != null ? other : "#";
	}

	public boolean children(Long pid) {
		return pid != null && pid == id;
	}

	public List<MenuBuilder> childrens() {
		return childrens;
	}

	public boolean addChildren(MenuBuilder children) {
		if (this.childrens == null) {
			this.childrens = new ArrayList<>();
		}

		return childrens.add(children);
	}

	public String getIdentity() {
		return identity;
	}

	public void setActive(String other) {
		this.active = active || isActive(other);
	}

	@Override
	public String toString() {
		return builder.toString();
	}

}
